package com.dangdang.serviceImpl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.dangdang.domain.Product;
import com.dangdang.service.ProductService;
import com.dangdang.util.HbnUtils;

/**
 * 商品类别管理实现类
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-1-19
 */
public class ProductServiceImpl implements ProductService {

	/**
	 * 添加一个商品
	 */
	@Override
	public Product addProduct(Product product) {
		Session s = HbnUtils.getSession();
		try {
			s.beginTransaction();
			s.save(product);
			s.getTransaction().commit();
		} catch (Exception e) {
			s.getTransaction().rollback();
		} finally {
			s.close();
		}
//		Session session = HbnUtils.getSession();
//		Query query = session.createQuery("from Product where productName = ?");
//		Product p = (Product)query.setParameter(0, product.getProductName()).list().get(0);
//		session.close();
		return null;

	}

	/**
	 * 根据商品ID删除一个商品<br>
	 * 将我要删除的商品条目在数据库中加以标识，
	 */
	@Override
	public void deleteProduct(Product product) {
		Session s = HbnUtils.getSession();
		try {
			product.setHasDeleted(1);
			s.beginTransaction();
			s.update(product);
			s.getTransaction().commit();
		} catch (Exception e) {
			s.getTransaction().rollback();
		} finally {
			s.close();
		}

	}

	/**
	 * 获得所有的商品
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Product> findAllProduct() {
		Session s = HbnUtils.getSession();
		Query query = s.createQuery("from Product");
		List<Product> productList = query.list();
		s.close();
		return productList;

	}

	/**
	 * 根据商品ID获得指定的商品
	 */
	@Override
	public Product findProductById(Integer productId) {
		Session s = HbnUtils.getSession();
		String hql = "from Product where id = ?";
		Query query = s.createQuery(hql);
		query.setParameter(0, productId);
		Product product = (Product) query.uniqueResult();
		s.close();
		return product;
	}

	/**
	 * 更新商品的信息
	 */
	@Override
	public void updateProduct(Product product) {
		Session s = HbnUtils.getSession();
		try {
			s.beginTransaction();
			s.update(product);
			s.getTransaction().commit();
		} catch (Exception e) {
			s.getTransaction().rollback();
		} finally {
			s.close();
		}
	}

}
